package org.linlinjava.litemall.web.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.util.bcrypt.BCryptPasswordEncoder;
import org.linlinjava.litemall.db.dao.LitemallAdminMapper;
import org.linlinjava.litemall.db.domain.LitemallAdmin;
import org.linlinjava.litemall.db.domain.LitemallRole;
import org.linlinjava.litemall.db.domain.LumiereAbnormalSettlement;
import org.linlinjava.litemall.db.service.LitemallAdminService;
import org.linlinjava.litemall.db.service.LitemallRoleService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.linlinjava.litemall.db.service.LumiereAbnormalSettlementService;
import org.linlinjava.litemall.web.dto.AdminSettlementRecordDTO;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.time.LocalDateTime;
import java.util.List;

import static org.linlinjava.litemall.web.util.WebResponseCode.*;

@Service
@RequiredArgsConstructor
public class WebConfigService extends ResponseUtil {

    private final LitemallAdminMapper litemallAdminMapper;

    /**
     * litemall角色服务
     */
    private final LitemallRoleService litemallRoleService;

    /**
     * 卢米埃异常结算服务
     */
    private final LumiereAbnormalSettlementService lumiereAbnormalSettlementService;

    //操作权限组
    private final String[] rolesList = {
            "SuperAdmin",
            "Supervisor",
            "SM",
            "Assistant manager"
    };

    /**
     * 强制下班API
     *
     * @param username 用户名
     * @param password 密码
     */
    public Response forcedToWork(String username, String password,Integer shopId) {

        //得到当前输入的admin账号信息
        //admin的账号只能唯一才能实现该功能
        LitemallAdmin litemallAdmin = litemallAdminMapper.selectOne(Wrappers.lambdaQuery(LitemallAdmin.class).eq(LitemallAdmin::getUsername, username));
        if(ObjectUtil.isNull(litemallAdmin)){
            return ResponseUtil.fail("用户不存在");
        }
        //如果是店长角色
        if(litemallAdmin.getShopId()==null || litemallAdmin.getRoleIds()[0].equals("4") || !litemallAdmin.getShopId().equals(shopId)){
            return ResponseUtil.fail(INSUFFICIENT_ACCOUNT_PERMISSION,"账号权限不足,不是本店店长！");
        }
        if(ObjectUtil.isNull(litemallAdmin)){
            return ResponseUtil.fail(AUTH_INVALID_ACCOUNT,"账号不存在！");
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        boolean matches = encoder.matches(password, litemallAdmin.getPassword());
        if (!encoder.matches(password, litemallAdmin.getPassword())) {
            return ResponseUtil.fail(INCORRECT_ACCOUNT_PASSWORD, "账号密码错误！");
        }


        //遍历他的角色ID是否具有改权限
        for(Integer role: litemallAdmin.getRoleIds()){
            LitemallRole litemallRole = litemallRoleService.findById(role);
            for(String current : rolesList){
                if(current.equals(litemallRole.getName())){
                    return ResponseUtil.ok("强制下班成功！");
                }
            }
        }
        return ResponseUtil.fail(INSUFFICIENT_ACCOUNT_PERMISSION,"账号权限不足！");
    }

    /**
     * 结算记录
     *
     * @param userId 用户id
     * @return {@link Response}
     */
    public Response settlementRecord(Integer userId, Integer shopId, AdminSettlementRecordDTO settlementRecordDto) {
        //校验登录状态
        if(ObjectUtil.isEmpty(userId)){
            ResponseUtil.unlogin();
        }
        //记录数据库日志
        LumiereAbnormalSettlement lumiereAbnormalSettlement =new LumiereAbnormalSettlement();
        lumiereAbnormalSettlement.setUserId(userId);
        lumiereAbnormalSettlement.setShopId(shopId);
        lumiereAbnormalSettlement.setTotalCash(settlementRecordDto.getTotalCash());
        lumiereAbnormalSettlement.setDeserveCash(settlementRecordDto.getDeserveCash());
        lumiereAbnormalSettlement.setDifferenceAmount(settlementRecordDto.getDifferenceAmountl());
        lumiereAbnormalSettlement.setDenominationMap(JSONUtil.toJsonStr(settlementRecordDto.getDenominationMap()));
        lumiereAbnormalSettlement.setAddTime(LocalDateTime.now());
        lumiereAbnormalSettlement.setUpdateTime(LocalDateTime.now());
        lumiereAbnormalSettlement.setDeleted(0);
        boolean save = lumiereAbnormalSettlementService.save(lumiereAbnormalSettlement);
        return save?ResponseUtil.ok(lumiereAbnormalSettlement):ResponseUtil.fail();
    }
}
